﻿using BCCommon;
using BCEntity.OA.BusinessFlowRecord;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;

namespace BCData.OA.BusinessFlowRecord
{
    /// <summary>
    /// OA系统业务流记录
    /// </summary>
	public class BusinessFlowRecordData : IBusinessFlowRecordData
    {
        private readonly IDatabaseContext databaseContext;
        private const string QUERY_EXISTS = @"SELECT 1 FROM OA_BusinessFlowRecord";
        private const string QUERY = @"SELECT BusinessFlowRecordId,BusinessFlowModelCode,ReferenceNo,RecordTitle,IsInitialized,IsInitFailed,FailedRemark,CreateTime,InitializedTime,
                                            BusinessFlowInstanceId,IsClosed,CloseAdminId,CloseAdminName,CloseTime,CloseRemark,IsCompleted
                                        FROM OA_BusinessFlowRecord";
        public BusinessFlowRecordData(IDatabaseContext databaseContext)
        {
            this.databaseContext=databaseContext;
        }

        public async Task<bool> Exists(long businessFlowRecordId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowRecordId=?BusinessFlowRecordId", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowRecordId", businessFlowRecordId, DbType.Int64);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<bool> Exists(string businessFlowModelCode, string referenceNo)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode AND ReferenceNo=?ReferenceNo AND IsInitialized=1 AND IsClosed=0 AND IsCompleted=0", QUERY_EXISTS);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode, DbType.AnsiString);
            parameters.Add("?ReferenceNo", referenceNo, DbType.AnsiString);
            return await this.databaseContext.Slave.ExecuteScalarAsync(sql, parameters) != null;
        }

        public async Task<BusinessFlowRecordEntity> Add(BusinessFlowRecordEntity entity)
        {
            string sql = SqlCommands.GetInsertSql("OA_BusinessFlowRecord", new string[] { "BusinessFlowModelCode", "ReferenceNo", "RecordTitle" });
            sql = string.Format("{0} {1} WHERE BusinessFlowRecordId=LAST_INSERT_ID();", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ReferenceNo", entity.ReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?RecordTitle", entity.RecordTitle?.Trim(), DbType.AnsiString, size: 50);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowRecordEntity>(sql, parameters, databaseContext.Transaction);

        }

        public async Task<BusinessFlowRecordEntity> Update(BusinessFlowRecordEntity entity)
        {
            string sql = SqlCommands.GetUpdateSql("OA_BusinessFlowRecord", new string[] { "BusinessFlowModelCode", "ReferenceNo", "RecordTitle", "IsInitialized", "IsInitFailed",
                "FailedRemark", "InitializedTime","BusinessFlowInstanceId","IsClosed","CloseAdminId","CloseAdminName","CloseTime","CloseRemark","IsCompleted"}, new string[] { "BusinessFlowRecordId" });
            sql = string.Format("{0} {1} WHERE BusinessFlowRecordId=?BusinessFlowRecordId;", sql, QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowRecordId", entity.BusinessFlowRecordId, DbType.Int64, size: 20);
            parameters.Add("?BusinessFlowModelCode", entity.BusinessFlowModelCode?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?ReferenceNo", entity.ReferenceNo?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?RecordTitle", entity.RecordTitle?.Trim(), DbType.AnsiString, size: 50);
            parameters.Add("?IsInitialized", entity.IsInitialized, DbType.Boolean);
            parameters.Add("?IsInitFailed", entity.IsInitFailed, DbType.Boolean);
            parameters.Add("?FailedRemark", entity.FailedRemark?.Trim(), DbType.String);
            parameters.Add("?InitializedTime", entity.InitializedTime, DbType.DateTime);
            parameters.Add("?BusinessFlowInstanceId", entity.BusinessFlowInstanceId, DbType.Int64, size: 20);
            parameters.Add("?IsClosed", entity.IsClosed, DbType.Boolean);
            parameters.Add("?CloseAdminId", entity.CloseAdminId, DbType.Int64,size:20);
            parameters.Add("?CloseAdminName", entity.CloseAdminName, DbType.AnsiString,size:20);
            parameters.Add("?CloseTime", entity.CloseTime, DbType.DateTime);
            parameters.Add("?CloseRemark", entity.CloseRemark?.Trim(), DbType.String);
            parameters.Add("?IsCompleted", entity.IsCompleted, DbType.Boolean);
            return await this.databaseContext.Master.QueryFirstOrDefaultAsync<BusinessFlowRecordEntity>(sql, parameters, databaseContext.Transaction);
        }

        public async Task<bool> Delete(long businessFlowRecordId)
        {
            string sql = @"DELETE FROM OA_BusinessFlowRecord WHERE BusinessFlowRecordId=?BusinessFlowRecordId";
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowRecordId", businessFlowRecordId, DbType.Int64);
            return await this.databaseContext.Master.ExecuteAsync(sql, parameters, databaseContext.Transaction) > 0;
        }

        public async Task<BusinessFlowRecordEntity> GetEntity(long businessFlowRecordId)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowRecordId=?BusinessFlowRecordId", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowRecordId", businessFlowRecordId, DbType.Int64);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowRecordEntity>(sql, parameters);
        }

        public async Task<BusinessFlowRecordEntity> GetEntity(string businessFlowModelCode, string referenceNo)
        {
            string sql = string.Format(@"{0} WHERE BusinessFlowModelCode=?BusinessFlowModelCode AND ReferenceNo=?ReferenceNo AND IsInitialized=1 AND IsClosed=0 AND IsCompleted=0", QUERY);
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?BusinessFlowModelCode", businessFlowModelCode?.Trim(), DbType.AnsiString);
            parameters.Add("?ReferenceNo", referenceNo?.Trim(), DbType.AnsiString);
            return await this.databaseContext.Slave.QueryFirstOrDefaultAsync<BusinessFlowRecordEntity>(sql, parameters);
        }

        public async Task<IEnumerable<BusinessFlowRecordEntity>> GetList()
        {
            string sql = string.Format("{0} WHERE IsInitFailed=0 AND IsInitFailed=0 ORDER BY BusinessFlowRecordId DESC", QUERY);
            return await this.databaseContext.Slave.QueryAsync<BusinessFlowRecordEntity>(sql);
        }

        public async Task<(IEnumerable<BusinessFlowRecordEntity>, int)> Query(string businessFlowModelCode, string referenceNo, bool? isInitialized, bool? isInitFailed, DateTime? start, DateTime? end, int pageIndex, int pageSize)
        {
            List<string> wheres = new List<string>();
            DynamicParameters parameters = new DynamicParameters();
            if (!string.IsNullOrWhiteSpace(businessFlowModelCode))
            {
                wheres.Add("BusinessFlowModelCode=?BusinessFlowModelCode");
                parameters.Add("?BusinessFlowModelCode", businessFlowModelCode?.Trim(), DbType.AnsiString);
            }
            if (!string.IsNullOrWhiteSpace(referenceNo))
            {
                wheres.Add("ReferenceNo=?ReferenceNo");
                parameters.Add("?ReferenceNo", referenceNo?.Trim(), DbType.AnsiString);
            }
            if (isInitialized.HasValue)
            {
                wheres.Add("IsInitialized=?IsInitialized");
                parameters.Add("?IsInitialized", isInitialized, DbType.Boolean);
            }
            if (isInitFailed.HasValue)
            {
                wheres.Add("IsInitFailed=?IsInitFailed");
                parameters.Add("?IsInitFailed", isInitFailed, DbType.Boolean);
            }
            if (start.HasValue && !end.HasValue)
            {
                wheres.Add("CreateTime>=?Start");
                parameters.Add("?Start", start.Value, DbType.DateTime);
            }
            else if (!start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime<=?End");
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            else if (start.HasValue && end.HasValue)
            {
                wheres.Add("CreateTime>=?Start AND CreateTime<=?End");
                parameters.Add("?Start", start.Value, DbType.DateTime);
                parameters.Add("?End", end.Value, DbType.DateTime);
            }
            string sql = string.Format(@"{0} {1} ORDER BY CreateTime DESC LIMIT {2},{3}; SELECT COUNT(1) FROM OA_BusinessFlowRecord {1}",
                   QUERY,
                   wheres.Count > 0 ? " WHERE " + string.Join(" AND ", wheres) : "",
                   (pageIndex - 1) * pageSize,
                   pageSize);
            return await this.databaseContext.Slave.QueryPageableListAsync<BusinessFlowRecordEntity>(sql, parameters);
        }
    }
}



